package com.jrfid.smartcabinet.demo.ui.add_nfc

import android.app.Application
import android.view.View
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavController
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.jrfid.devicemanager.library.DeviceType
import com.jrfid.devicemanager.library.DevicesManager
import com.jrfid.devicemanager.library.packet.ICCardPacketData
import com.jrfid.smartcabinet.demo.R
import com.jrfid.smartcabinet.demo.base.BaseViewModel
import com.jrfid.smartcabinet.demo.db.AppDatabase
import com.jrfid.smartcabinet.demo.db.entity.NFCInfoEntity
import com.jrfid.smartcabinet.demo.model.TagInfoModel
import com.jrfid.smartcabinet.demo.utils.Config
import com.jrfid.smartcabinet.demo.utils.KTDataUtils
import com.jrfid.smartcabinet.demo.utils.TCPConnectUtils
import com.xuhao.didi.core.iocore.interfaces.ISendable
import com.xuhao.didi.core.pojo.OriginalData
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager
import kotlinx.coroutines.launch
import java.lang.Exception

class AddNFCViewModel(application: Application, navController: NavController) : BaseViewModel(application, navController) {

    //    private val socketListener = object : SocketActionAdapter() {
//        override fun onSocketConnectionSuccess(info: ConnectionInfo?, action: String?) {
//            super.onSocketConnectionSuccess(info, action)
//            LogUtils.dTag(TAG, "连接成功")
//        }
//
//        override fun onSocketConnectionFailed(info: ConnectionInfo, action: String?, e: Exception?) {
//            super.onSocketConnectionFailed(info, action, e)
//            ToastUtils.showShort(getString(R.string.text_connect_error))
//            LogUtils.dTag(TAG, "连接失败")
//        }
//
//        override fun onSocketDisconnection(info: ConnectionInfo, action: String?, e: Exception?) {
//            super.onSocketDisconnection(info, action, e)
//            ToastUtils.showShort(getString(R.string.text_connect_error_disconnect))
//            LogUtils.dTag(TAG, "连接断开")
//        }
//
//        override fun onSocketReadResponse(info: ConnectionInfo, action: String, data: OriginalData) {
//            super.onSocketReadResponse(info, action, data)
//            val body = data.bodyBytes
//            val header = data.headBytes
//            LogUtils.dTag(TAG, "${info.ip}收到数据：${KTDataUtils.byteArrayToHex(header)} ${KTDataUtils.byteArrayToHex(body)}")
//            LogUtils.dTag(TAG, "${info.ip}收到数据：${String(header)} ${String(body)}")
//            val no = "${String(header)}${String(body)}"
//            val entity = AppDatabase.instance.getNFCInfoDao().findByCardNo(no)
//            if (entity != null) {
//                ToastUtils.showShort(getString(R.string.text_ic_registered))
//                return
//            }
//            AppDatabase.instance.getNFCInfoDao().insert(NFCInfoEntity().apply { this.card = no })
//            ToastUtils.showShort(getString(R.string.text_ic_register_successfully))
//        }
//
//        override fun onSocketWriteResponse(info: ConnectionInfo, action: String?, data: ISendable) {
//            super.onSocketWriteResponse(info, action, data)
//            LogUtils.dTag(TAG, "${info.ip}发送数据：${KTDataUtils.byteArrayToHex(data.parse())}")
//        }
//    }
//
//    private var manager: IConnectionManager? = null
//    private val onReceiveICCardListener = object : Manager.OnSerialPortDataListener {
//        override fun onDataReceived(byteArray: ByteArray) {
//            LogUtils.d("main recv: ${KTDataUtils.byteArrayToHexTrim(byteArray)}")
//            val len = byteArray[1].toInt()
//            val dataLen = len - 3
//            val cmd = byteArray[3]
//            when (cmd) {
//                CMDData.Cabinet.CMD_IC_ID_CARD_DATA -> {
//                    val cardData = ByteArray(dataLen)
//                    System.arraycopy(byteArray, 4, cardData, 0, cardData.size)
//                    val cardNo = KTDataUtils.byteArrayToHexTrim(cardData)
//                    LogUtils.d("ic recv:${cardNo}")
//                    if (cardData[0] == 0x02.toByte() && cardData[cardData.size - 1] == 0x03.toByte()) {
//                        viewModelScope.launch {
//                            val entity = AppDatabase.instance.getNFCInfoDao().findByCardNo(cardNo)
//                            if (entity != null) {
//                                ToastUtils.showShort(getString(R.string.text_ic_registered))
//                            } else {
//                                AppDatabase.instance.getNFCInfoDao().insert(NFCInfoEntity().apply { this.card = cardNo })
//                                ToastUtils.showShort(getString(R.string.text_ic_register_successfully))
//                            }
//                        }
//                    }
//                }
//            }
//        }
//
//        override fun onDataSend(byteArray: ByteArray) {
//
//        }
//
//    }

    private val listener = object : DevicesManager.OnDeviceDataCallback {
        override fun onDataReceived(deviceType: DeviceType, address: Byte, byteArray: ByteArray) {
            if (deviceType == DeviceType.IDCard) {
                val model = ICCardPacketData(byteArray)
                addICCard(model.getICCardNo())
            }
        }

        override fun onDataSend(deviceType: DeviceType, address: Byte, byteArray: ByteArray) {

        }

    }

    private fun addICCard(no: String) {
        viewModelScope.launch {
            val entity = AppDatabase.instance.getNFCInfoDao().findByCardNo(no)
            if (entity != null) {
                ToastUtils.showShort(getString(R.string.text_ic_registered))
            } else {
                AppDatabase.instance.getNFCInfoDao().insert(NFCInfoEntity().apply { this.card = no })
                ToastUtils.showShort(getString(R.string.text_ic_register_successfully))
            }
        }
    }

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        val list = Config.getCabinetList()
        if (list.isEmpty()) {
            ToastUtils.showShort(getString(R.string.text_config_cabinet_info))
        } else {
            //获取主柜信息
            val info = list[0]
//            manager = TCPConnectUtils.connectNFCDevice(info.icIP.get(), info.icPort.get()?.toIntOrNull(), socketListener)

        }
        DevicesManager.instance.addOnDeviceDataListener(listener)
//        MainBoardManager.instance.addOnSerialPortDataListener(onReceiveICCardListener)
    }


    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        DevicesManager.instance.removeOnDeviceDataListener(listener)
//        MainBoardManager.instance.removeOnSerialPortDataListener(onReceiveICCardListener)
//        manager?.unRegisterReceiver(socketListener)
    }

    fun onClickBtnBack(view: View) {
        navController.navigateUp()
    }

}